<template>
  <div class='index-container'>
    <van-nav-bar title='现场直播' left-arrow @click-left='onClickLeft' ref='nav' />
    <!-- <div class='div-container' v-bind:style='{ marginTop: `${navBarHeight}px` }' v-if='liveTitle'> -->
    <div class='div-container' v-bind:style='{ marginTop: `${navBarHeight}px` }' v-if='true'>
      <div v-bind:style='{ height: `calc(${innerHeight}px - ${navBarHeight}px ` }'>
        <div class='conts' ref='cont'>
          <!-- <div>
            <iframe src="https://wx.vzan.com/live/m/vzliveplayer?type=live&vid=385168348&liveId=182313"></iframe>
          </div> -->
          <!-- <div>
            <video id="vzanvideo"></video>
          </div> -->
          <div ref='player' class='player-d'></div>
          <div class='video-error' v-if='videoError'>
            <div class='error_msg'>播放失败，请检查播放源的有效性</div>
          </div>
          <div class='living' v-if='living'>直播中</div>
          <div class='container'>
            <div class='title'>{{ liveTitle }}</div>
            <div class='tab'>
              <div style='display: flex'>
                <div class='tab-title' @click='getLive(0)' :class="isActive == 0 ? 'on' : ''" v-if="enableLike">直播点赞</div>
                <div class='tab-title' style='margin-left: 43px' @click='getLive(1)' :class="isActive == 1 ? 'on' : ''"
                  v-if="enablePopularity">
                  人气榜
                </div>
              </div>
              <div class='pic-live' v-if='enablePictureLive' @click='picLive'>进入图片直播</div>
            </div>
          </div>
        </div>
        <div class='ranking'
        v-show='isActive === 0' 
          v-bind:style='{ height: `calc(100vh - ${navBarHeight}px - ${contHeight}px)` }'>
          <Like mystyle='position: absolute; left: 15%; z-index: 9999999' ref='like'></Like>
          <div class='ranking-tip' @click='getShow'>
            <img src='../../assets/img/game/icon2.png' alt='' />
          </div>
          <div class='liveing' style='overflow: hidden'
            v-bind:style='{ height: `calc(100vh - ${navBarHeight}px - ${contHeight}px - 18px)` }' ref='wrapper2'>
            <div class='flex' v-if='enableLike && likeList.length > 0'>
              <div class='item' v-for='(item, index) in likeList' :key='index'>
                <div class='num'>
                  {{ item.bank.name }}
                </div>
                <div class='name line1' style='display: block;'>
                  {{ item.name }}
                  <img src='../../assets/img/live/like.png' v-if='item.is_like === 1' alt='' />
                </div>
                <div class='btn' @click='getLike(item)'>
                  <div>
                    为Ta点赞
                  </div>
                </div>
              </div>
            </div>
            <van-empty v-else description='暂无数据' />
          </div>

        </div>
        <div class='ranking popularity-wrap' v-show='isActive == 1'
          v-bind:style='{ height: `calc(100vh - ${navBarHeight}px - ${contHeight}px)` }'>
          <div class='ranking-container' style='position: relative; overflow: hidden'
            v-bind:style='{ height: `calc(100vh - ${navBarHeight}px - ${contHeight}px - 18px) ` }'>
            <div style='position: sticky; top: 0px' class='ranking-title' ref='top3'>
              <div class='item tc w16'>排行</div>
              <div class='item tc ml2'>编号姓名</div>
              <div class='item tc ml2'>所属分行</div>
              <div class='item tc'>出彩值</div>
            </div>
            <div class='ranking-items' ref='wrapper' style='height: 100%'>
              <div class='items' v-if='enablePopularity && hot.list.length > 0'>
                <div class='ranking-item' v-for='(item, index) in hot.list' :key='index'>
                  <div class='item tc w16' style='display: flex;justify-content: center;align-items: center'>
                    <div class='img' :class="index === 0 ? '' : 'on'">
                      {{ ++index }}
                    </div>
                  </div>
                  <div class='name chung item tc ml2'>
                    {{ joinZero(item.id) + ' ' + item.name }}
                  </div>
                  <div class='addres item tc ml2'>
                    {{ item.bank.name }}
                  </div>
                  <div class='add-like item tc'>
                    {{ item.likes_num }}
                  </div>
                </div>
              </div>
              <van-empty v-else description='暂无数据' />
            </div>
          </div>
        </div>
        <van-popup v-model='isShow'>
          <div class='search-popup'>
            <div class='title'>
              直播点赞通道开启后，观众可以为自己喜欢的选手点赞，可以为多位选手点赞，但每个ID只限给同个选手点赞1次。
            </div>
            <div class='confirm' @click='getShow'>确定</div>
          </div>
        </van-popup>
      </div>
    </div>
    <van-empty v-else description='暂无直播' style='background-color: #FAFAFA;' />
  </div>
</template>

<script>
import BScroll from '@better-scroll/core'
import Like from '@/components/like'
import { mapGetters } from 'vuex'
import { liveCompetitor, liveInfo, uplike, hotRank } from '@/api/live.js'
import { Toast } from 'vant'
import { parseTime } from '../../utils'
import DPlayer from 'dplayer'

export default {
  components: { Like },
  data() {
    return {
      bs: null,
      bs2: null,
      isPullUpLoad: false,
      contHeight: 0,
      navBarHeight: 0,
      isShow: false,
      top3Height: 0,
      isActive: 0,
      initialized: false,
      liveTitle: '',
      liveId: 0, // 直播ID
      liveCompetitorId: 0, // 点赞场次ID
      enableLike: false, // 是否开启点赞帮
      enablePictureLive: false, // 是否开启图片直播
      enablePopularity: false, // 是否开启排行榜
      pictureLiveUrl: false, // 图片直播地址
      living: false, // 是否在直播
      playerOptions: {},
      videoError: false,
      list: [2, 2],
      likeList: [],
      hot: {
        list: [],
        page: 1,
        size: 10
      },
      innerHeight: 0,
      player: null
    }
  },
  computed: {
    ...mapGetters(['tabBarHeight'])
  },
  created() {
  },
  activated() {
    this.getList()
  },
  mounted() {
    // this.player = new VZANPlayer("vzanvideo", {
    //   playerType: "common", // sdk类型
    //   liveId: 182313, // 直播间id
    //   type: "live", // 视频源类型
    //   vid: 385168348, // 视频源id
    //   fullscreen: false // 设置H5端设置页面全屏或非页面全屏（开启后，支持IOS微信浏览器显示跑马灯。）
    //   // marqueeConfig: {
    //   //   value: "测试跑马灯",
    //   //   fontColor: "red",
    //   //   fontSize: "30px",
    //   // },
    // })
    this.getList()
    // this.contHeight = this.$refs.cont.offsetHeight
    this.navBarHeight = this.$refs.nav.$el.offsetHeight // 获取组件元素高度
    this.innerHeight = window.innerHeight
    //   this.init()
    window.addEventListener('resize', this.refreshScroll)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.refreshScroll)
  },
  methods: {
    refreshScroll() {
      this.bs2.scrollTo(0, 0, 100)
      this.bs.scrollTo(0, 0, 100)
      this.bs2?.refresh()
      this.bs?.refresh()
    },
    getList() {
      liveInfo().then(res => {
        if (res.code === 200) {
          const {
            picture_live_url,
            live_url,
            image,
            name,
            id,
            enable_like,
            enable_picture_live,
            enable_popularity,
            start_time,
            end_time
          } = res.data
          const nowTime = parseTime(new Date())
          if (start_time <= nowTime && end_time >= nowTime) {
            this.living = true
          }
          const playerOptions = {
            poster: image, // 你的封面地址
            src: live_url,
            height: 211 // 视频框的高度
          }
          this.liveTitle = name
          this.enablePictureLive = enable_picture_live
          this.enableLike = enable_like
          this.enablePopularity = enable_popularity
          this.pictureLiveUrl = picture_live_url
          this.liveId = id
          // 初始化播放器
          this.initPlayer(playerOptions)
          if (this.enableLike) {
            this.isActive = 0
            this.getLiveCompetitor()
          } else if (this.enablePopularity) {
            this.isActive = 1
            this.getHotRank()
          }
        }
      })
    },
    // 热力榜单
    getHotRank() {
      let id = this.liveId
      hotRank({ id }).then(res => {
        this.hot.list = res.data
        this.init()
      })
    },
    // 直播点赞
    getLiveCompetitor() {
      let id = this.liveId
      liveCompetitor({
        id
      }).then(likeUsers => {
        const { id, list } = likeUsers.data || {}
        this.liveCompetitorId = id || 0
        this.likeList = list || []
        this.contHeight = this.$refs.cont.offsetHeight

        this.init()
      })
    },

    initPlayer(playerOptions) {
      this.$nextTick(() => {
        // 初始化播放器
        const dp = new DPlayer({
          container: this.$refs.player,
          theme: '#FADFA3',
          lang: 'zh-cn',
          live: true,
          video: {
            pic: playerOptions.poster,
            url: playerOptions.src,
            type: 'hls',
            pluginOptions: {
              hls: {
                autoStartLoad: true,
                startPosition: -1
              }
            }
          }
        })
        dp.on('error', () => {
          this.videoError = true
        })

        document.getElementsByClassName('dplayer-icon dplayer-full-in-icon')[0].style.display = 'none'
      })
    },
    getShow() {
      this.isShow = !this.isShow
    },
    picLive() {
      if (this.pictureLiveUrl) {
        window.location.href = this.pictureLiveUrl
      }
    },
    getLive(e) {
      this.isActive = e
      if (e == 0) {
        this.getLiveCompetitor()
        this.isActive = 0
      } else if (e == 1) {
        this.getHotRank()
      }
      this.top3Height = this.$refs.top3.offsetHeight
      // this.init()
    },

    // 前补0
    joinZero(num) {
      if ((num + '').length > 3) {
        return num
      } else {
        return (Array(3).join('0') + num).slice(-3)
      }
    },
    // 播放状态改变回调
    playerStateChanged(playerCurrentState) {
      console.log('player current update state', playerCurrentState)
      // if (playerCurrentState.error === true) {}
    },

    /**
     * 视频播放器初始化
     */
    onPlayerReadied() {
      if (!this.initialized) {
        console.log('准备好了')
        this.initialized = true
      }
    },
    /**
     * 分片加载时间
     * @param e
     */
    onTimeupdate(e) {
      console.log('currentTime', e.cache_.currentTime)
    },
    // 点赞
    getLike(user) {
      if (user.is_like === 1) {
        return Toast.fail('您已经为Ta点过赞了')
      }
      uplike({
        rel_id: this.liveCompetitorId, // 场次ID
        competitor_id: user.id // 选手id
      }).then(res => {
        if (res.code === 200) {
          user.is_like = 1
          this.$refs.like.setHidden()
        }
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    init() {
      this.$nextTick(() => {
        const option = {
          startY: 0,
          scrollY: true,
          probeType: 3,
          stopPropagation: true,
          click: true,
          bounce: true
        }
        if (this.$refs.wrapper) {
          this.bs = new BScroll(this.$refs.wrapper, option)
        }
        if (this.$refs.wrapper2) {
          this.bs2 = new BScroll(this.$refs.wrapper2, option)
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped>
@import '../../assets/css/video.scss';
@import './css/detail.scss';

.none {
  display: none;
}

.video-error {
  position: absolute;
  left: auto;
  font-size: 16px;
  color: red;
  z-index: 9999;
  top: 100px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.error_msg {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  color: #fff;
  background-color: #000000;
}

.player-d {
  height: 211px
}

/* .popularity-wrap {

  .ranking-container {
    display: flex;
    flex-direction: column;

    .ranking-title {
      flex: 0 0 auto;

    }

    .ranking-items {
      flex: 1;
    }
  }

} */
</style>
